﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TeachingAffairsManagementSystem.WebControl;

namespace TeachingAffairsManagementSystem
{
    public partial class Login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        protected void BtnLogin_Click(object sender, EventArgs e)
        {
            string username = TBUserName.Text;
            string password = TBPassword.Text;
            bool isRememberMe = CBRememberMe.Checked;
            // 判断数据
            if (username =="")
            {
                Alert.Show("用户名不能为空", AlertBox.Level.Danger, true);
                return;
            }

            if (password=="")
            {
                Alert.Show("密码不能为空", AlertBox.Level.Danger, true);
                return;
            }
            DataSet loginDataSet = Operation.Login(username, password);
            if (loginDataSet.Tables[0].Rows.Count > 0)
            {
                // 登录成功
                DataRow loginDataRow = loginDataSet.Tables[0].Rows[0];
                string userType = (string) loginDataRow["user_type"];
                int id = Convert.ToInt32(loginDataRow["id"]);
                string name = (string) loginDataRow["name"];
                if (isRememberMe)
                {
                    // 记住我
                    // 设置cookies
                    HttpCookie loginDataCookie = new HttpCookie("login_data");
                    loginDataCookie.Values["username"] = username;
                    loginDataCookie.Values["password"] = password;
                    loginDataCookie.Expires = DateTime.Now.AddDays(7);
                    Response.Cookies.Add(loginDataCookie);
                }

                // 设置session 保持登录状态
                Session["isLoggedIn"] = true;
                Session["userType"] = userType;
                Session["id"] = id;
                Session["name"] = name;
                Response.Redirect("~/Main.aspx");
            }

            else
            {
                // 登录失败
                Alert.Show("登录失败，请检查用户名或密码", AlertBox.Level.Danger, true);
            }
        }
    }
}